package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuditServiceImpl implements IAuditService {

    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    @Lazy
    private IWmNewsService wmNewsService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private IWmChannelService channelService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    @Async
    public void audit(Integer id) {
        WmNews wmNews = wmNewsService.getById(id);
        audit(wmNews);
    }

    @Override
    @Async
    public void audit(WmNews wmNews) {
        boolean isPass = true;

        //自管理敏感词审核
        isPass = checkSensitive(wmNews);
        if (!isPass) return;


        //阿里云文本审核
        isPass = checkText(wmNews);
        if (!isPass) return;
        //阿里云的图片审核
        isPass = checkImage(wmNews);
        if (!isPass) return;
        //保存app的文章
        //判断现在的时间是不是已经到达了发布时间
        if (System.currentTimeMillis() >= wmNews.getPublishTime().getTime()) {
            Long articleId = saveArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(9);
        } else {
            wmNews.setStatus(8);


            //使用Redisson做延迟任务
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("news-dqueue");
            //根据blockingDeque获取延迟队列
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //放数据
            //即将发布的时间-当前时间
            long time = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
            delayedQueue.offer(wmNews.getId(), time, TimeUnit.MILLISECONDS);
            log.info("延迟消息发送成功，预计在" + time + "毫秒后，会执行某一个方法" + new Date());


        }
        wmNewsService.updateById(wmNews);

    }

    @Autowired
    private IWmSensitiveService wmSensitiveService;

    private boolean checkSensitive(WmNews wmNews) {
        //初始化DFA算法的大map
        List<WmSensitive> wmSensitiveList = wmSensitiveService.list();
//        List<String> stringList = wmSensitiveList.stream().map(s -> s.getSensitives()).collect(Collectors.toList());
        List<String> stringList = new ArrayList<>();
        for (WmSensitive wmSensitive : wmSensitiveList) {
            stringList.add(wmSensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(stringList);

        //检查文章文本中是否包含敏感词
        //文本包括：文章标题+文章的内容
        String text = wmNews.getTitle();

        //从Content中提取文本
        List<ContentDto> contentDtos = JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text += contentDto.getValue();
            }
        }
        Map<String, Integer> matchWordsMap = SensitiveWordUtil.matchWords(text);
        if (matchWordsMap.size() == 0) {
            //审核通过
            return true;
        } else {
            wmNews.setStatus(2);
            //审核不通过或需要人工审核的原因
//            String label = (String) map.get("label");
            Set<String> strings = matchWordsMap.keySet();
            String reason = String.join(",", strings);

            wmNews.setReason("自管理敏感词审核未通过，原因是内容中包含：" + reason);
            wmNewsService.updateById(wmNews);
            //审核驳回
            return false;
        }


    }


    public Long saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
        articleDto.setId(null);

        //app用户可以申请成自媒体用户,自媒体用户自动就是文章作者
        //获取自媒体用户，自媒体用户中有AuthorId
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserService.getById(userId);
        articleDto.setAuthorId(wmUser.getApAuthorId());
        articleDto.setAuthorName(wmUser.getName());
        articleDto.setChannelId(wmNews.getChannelId());
        WmChannel wmChannel = channelService.getById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag(0);

        List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        List<String> urlList = new ArrayList<>();
        for (ImageDto imageDto : imageDtoList) {
            urlList.add(imageDto.getUrl());
        }
        articleDto.setImages(JSON.toJSONString(urlList));
        ResponseResult<Long> longResponseResult = articleFeign.saveArticle(articleDto);

        Long articleId = longResponseResult.getData();
        return articleId;


    }

    private boolean checkText(WmNews wmNews) {
        //文本包括：文章标题+文章的内容
        String text = wmNews.getTitle();

        //从Content中提取文本
        List<ContentDto> contentDtos = JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text += contentDto.getValue();
            }
        }

        boolean isPass = false;
        try {
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    isPass = true;
                    break;
                case "review":
                    wmNews.setStatus(3);
                    //审核不通过或需要人工审核的原因
                    wmNews.setReason("阿里云文本审核未通过，需要人工审核，原因是：" + map.get("label"));
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
                case "block":
                    wmNews.setStatus(2);
                    //审核不通过或需要人工审核的原因
                    wmNews.setReason("阿里云文本审核未通过，原因是：" + map.get("label"));
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isPass;
    }

    private boolean checkImage(WmNews wmNews) {

        boolean isPass = false;

        //图片包括：文章内容图片+文章的封面图片
        //获取封面图片
        String coverImages = wmNews.getImages();
        List<ImageDto> imageDtoList = JSON.parseArray(coverImages, ImageDto.class);
        //从Content中提取文本
        List<ContentDto> contentDtos = JSON.parseArray(wmNews.getContent(), ContentDto.class);
        //需要把内容图片放到imageDtoList中
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                //判断是否有重复的，如果有就不再放入了
                if (!imageDtoList.contains(imageDto)) {
                    imageDtoList.add(imageDto);
                }
            }
        }

        try {
            //imageDtoList:封面图片+内容图片
            List<byte[]> imageList = new ArrayList<>();
            //把图片都转成字节数组
            for (ImageDto imageDto : imageDtoList) {
                InputStream inputStream = minIOService.download(imageDto.getUrl());
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");


            switch (suggestion) {
                case "pass":
                    isPass = true;
                    break;
                case "review":
                    wmNews.setStatus(3);
                    wmNews.setReason("阿里云图片审核未通过，需要人工审核，原因是：" + map.get("label"));
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
                case "block":
                    wmNews.setStatus(2);
                    wmNews.setReason("阿里云图片审核未通过，原因是：" + map.get("label"));
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isPass;
    }
}